#include "adcConvertData.h"
#include "adc.h"
#include "string.h"

#define SAMPLE_CHANNEL			6
#define ADC_SAMPLE_MAX			60


uint16_t  ADC_ConvertedValue[ADC_SAMPLE_MAX] = {0x00};
uint32_t adcValueTotal[SAMPLE_CHANNEL] = {0};



void adcStartInitial(void)
{
	HAL_ADC_Start_DMA(&hadc1,(uint32_t*)ADC_ConvertedValue,ADC_SAMPLE_MAX);
}



uint16_t getAdcData(adcType type)
{
	uint16_t rtlValue;
	rtlValue = adcValueTotal[type];
	return rtlValue	;
}

	

void adcSampleEntry(void)
{
	uint8_t i;
	uint8_t j;
	uint8_t k;
	uint16_t temp;
	uint16_t  adcValue[ADC_SAMPLE_MAX] = {0x00};	
	uint16_t  adcArrary[SAMPLE_CHANNEL][ADC_SAMPLE_MAX/SAMPLE_CHANNEL] = {0x00};
	
	memcpy(adcValue, ADC_ConvertedValue,ADC_SAMPLE_MAX * 2);
	
	//value group
	for(i = 0; i < SAMPLE_CHANNEL; i ++)
	{
		for(j = 0; j < ADC_SAMPLE_MAX/SAMPLE_CHANNEL; j ++)
		{
			adcArrary[i][j] = adcValue[j * SAMPLE_CHANNEL + i];
		}
	}
	
	//Data sorting
	for(k = 0; k < SAMPLE_CHANNEL; k ++)
	{
		for(i =0; i < ADC_SAMPLE_MAX/SAMPLE_CHANNEL-1;i ++)
		{
			for(int j=0;j< ADC_SAMPLE_MAX/SAMPLE_CHANNEL-i-1; j++)
			{
				if(adcArrary[k][j]>adcArrary[k][j+1])
				{
					temp=adcArrary[k][j];
					adcArrary[k][j]=adcArrary[k][j+1];
					adcArrary[k][j+1]=temp;
				}
			}
		}
	}
	
	//Remove the maximum and minimum values then calculate the average value
	for(i = 0; i < SAMPLE_CHANNEL; i++)
	{
		adcValueTotal[i] = 0;
		for(j = 1;j < ADC_SAMPLE_MAX/SAMPLE_CHANNEL - 1; j ++)
		{
			adcValueTotal[i] += adcArrary[i][j];
		}
	}	
	for(i = 0; i < SAMPLE_CHANNEL; i++)
	{
			adcValueTotal[i] = adcValueTotal[i] / (ADC_SAMPLE_MAX/SAMPLE_CHANNEL -2) ;
	}
	
}




